/**
 * @Description: 状态-用户信息
 * @Author: rcc
 * @Date: 2024-8-30 12:52:50
 */

import { computed, ref } from 'vue'
import { defineStore } from 'pinia'

import { RoleTypes } from '@/types/enums.ts'
import type { User, UserData } from '@/types/api.d.ts'

export const useUserStore = defineStore('user', () => {
	const isLogin = ref(false)

	const userInfo = ref<User>({
		mobile: '',
		avatar: '',
		nickname: '',
		username: '',
		token: '',
	})
	const userCompany = ref<UserData['company'] | null>(null)

	const role = ref<RoleTypes>(RoleTypes.Job)

	const isJob = computed(() => {
		return role.value === RoleTypes.Job
	})

	const isHiring = computed(() => {
		return role.value === RoleTypes.Hiring
	})

	/**
	 * 获取用户信息
	 */
	const getUserInfo = async () => {
		const res = await uni.$u.post<UserData>('/user/info')

		if (res.code === 1) {
			userInfo.value = res.data.userinfo
			userCompany.value = res.data.company
			role.value = res.data.company === null ? RoleTypes.Job : RoleTypes.Hiring
		}
	}

	/**
	 * 检查是否登录
	 *
	 * @returns {Promise<boolean>} 登录状态.
	 */
	const checkToken = async () : Promise<boolean> => {
		const res = await uni.$u.post<UserData>('/user/info')

		if (res.code === 1) {
			userInfo.value = res.data.userinfo
			userCompany.value = res.data.company
			role.value = res.data.company === null ? RoleTypes.Job : RoleTypes.Hiring
		}

		isLogin.value = res.code === 1

		return isLogin.value
	}

	/**
	 * 设置用户信息
	 *
	 * @param {UserData} value - 用户信息.
	 */
	const setUserInfo = (value : UserData) => {
		userInfo.value = value.userinfo
		role.value = value.company === null ? RoleTypes.Job : RoleTypes.Hiring
	}

	return {
		role,
		userInfo,
		userCompany,
		isJob,
		isHiring,
		checkToken,
		getUserInfo,
		setUserInfo,
	}
})
